package org.csu.mybigpro.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.csu.mybigpro.domain.QuizGameSession;
import org.csu.mybigpro.persistence.QuizGameSessionMapper;
import org.csu.mybigpro.service.AiService;
import org.csu.mybigpro.service.IQuizGameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class QuizGameServiceImpl extends ServiceImpl<QuizGameSessionMapper, QuizGameSession> implements IQuizGameService {

    @Autowired
    private AiService aiService;

    @Autowired
    private QuizGameSessionMapper quizGameSessionMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public QuizGameSession startGame(String topic, String difficulty, Integer userId) throws Exception {
        // 1. 调用AI生成题目
        String prompt = "你是一个出题AI。请为我创建一个关于“" + topic + "”的知识问答挑战，难度为“" + difficulty + "”。" +
                "请严格返回一个JSON对象，该对象仅包含一个'questions'字段，其值为一个包含5个选择题的JSON数组。" +
                "每个问题对象必须包含: 'question'(题干), 'options'(Map格式的选项), 'answer'(正确答案的Key值)。";

        String rawResponse = aiService.generateExamFromDescription(prompt);

        // 【核心修复】使用健壮的JSON提取方法，而不是直接解析
        String cleanJson = extractJsonContent(rawResponse);

        JsonNode questionsNode = objectMapper.readTree(cleanJson);
        List<Map<String, Object>> questions = objectMapper.convertValue(questionsNode.path("questions"), new TypeReference<>() {});

        if (questions == null || questions.isEmpty()) {
            throw new Exception("AI未能成功生成题目，请稍后重试。");
        }

        // 2. 创建并保存游戏会话
        QuizGameSession session = new QuizGameSession();
        session.setUserId(userId);
        session.setTopic(topic);
        session.setQuestions(questions);
        session.setCurrentQuestionIndex(0);
        session.setScore(0);
        session.setStatus("IN_PROGRESS");
        session.setCreatedAt(LocalDateTime.now());

        quizGameSessionMapper.insert(session);
        return session;
    }

    @Override
    public Map<String, Object> submitAnswer(Long sessionId, int questionIndex, String answer) {
        QuizGameSession session = quizGameSessionMapper.selectById(sessionId);
        if (session == null || !session.getStatus().equals("IN_PROGRESS")) {
            return Map.of("error", "游戏会话无效或已结束。");
        }

        List<Map<String, Object>> questions = session.getQuestions();
        if (questionIndex >= questions.size()) {
            return Map.of("error", "问题索引超出范围。");
        }

        Map<String, Object> currentQuestion = questions.get(questionIndex);
        String correctAnswer = (String) currentQuestion.get("answer");
        boolean isCorrect = correctAnswer.equalsIgnoreCase(answer);

        if (isCorrect) {
            session.setScore(session.getScore() + 10); // 每题10分
        }

        session.setCurrentQuestionIndex(questionIndex + 1);

        boolean isGameOver = session.getCurrentQuestionIndex() >= questions.size();
        if (isGameOver) {
            session.setStatus("COMPLETED");
        }

        quizGameSessionMapper.updateById(session);

        return Map.of(
                "isCorrect", isCorrect,
                "correctAnswer", correctAnswer,
                "isGameOver", isGameOver,
                "score", session.getScore()
        );
    }

    /**
     * 【新增的辅助方法】: 从ExamServiceImpl中借鉴的、健壮的JSON提取逻辑
     * @param rawResponse 来自AI的原始响应字符串
     * @return 清理后的纯试卷JSON字符串
     */
    private String extractJsonContent(String rawResponse) {
        try {
            JsonNode rootNode = objectMapper.readTree(rawResponse);
            JsonNode textNode = rootNode.path("candidates").path(0).path("content").path("parts").path(0).path("text");

            if (!textNode.isMissingNode() && textNode.isTextual()) {
                return cleanRawText(textNode.asText());
            } else {
                return cleanRawText(rawResponse);
            }
        } catch (Exception e) {
            return cleanRawText(rawResponse);
        }
    }

    /**
     * 【新增的辅助方法】: 强力清理包含JSON的原始文本
     * @param text 可能包含JSON的脏文本
     * @return 提取出的纯JSON字符串
     */
    private String cleanRawText(String text) {
        String trimmedText = text.trim();
        int firstBrace = trimmedText.indexOf('{');
        int firstBracket = trimmedText.indexOf('[');

        int startIndex;
        if (firstBrace == -1 && firstBracket == -1) {
            return "{}";
        } else if (firstBrace != -1 && firstBracket != -1) {
            startIndex = Math.min(firstBrace, firstBracket);
        } else {
            startIndex = Math.max(firstBrace, firstBracket);
        }

        int lastBrace = trimmedText.lastIndexOf('}');
        int lastBracket = trimmedText.lastIndexOf(']');
        int endIndex = Math.max(lastBrace, lastBracket);

        if (endIndex > startIndex) {
            return trimmedText.substring(startIndex, endIndex + 1);
        }

        return "{}";
    }
}